<template>
  <el-card class="userinfo-container">
    <!-- 面板屑导航 -->
    <el-breadcrumb separator="/" style="margin-bottom: 40px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>基本资料</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form
      :model="infoForm"
      :rules="infoRuels"
      ref="infoRef"
      label-width="100px"
    >
      <el-form-item label="登录名称">
        <el-input v-model="infoForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="infoForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="infoForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
        <el-button @click="resetInfo">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { mapState, mapActions } from 'vuex'
import { reqUpdateUserInfo } from '../../api/user.js'
export default {
  name: 'UserInfo',
  computed: {
    ...mapState('user', ['userInfo'])
  },
  async created () {
    await this.getUserInfo()
    this.infoForm = { ...this.userInfo }
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    updateUserInfo () {
      // 1. 预校验
      this.$refs.infoRef.validate(async (boo) => {
        if (!boo) return ''
        // 2. 发送请求
        const { data } = await reqUpdateUserInfo(this.infoForm)
        // 3. 提示
        if (data.code !== 0) return this.$message.error(data.message)
        this.$message.success(data.message)
        // 4. 重新渲染 将vuex中的数据重新获取 调用getUserInfo
        this.getUserInfo()
      })
    },
    resetInfo () {
      this.infoForm = { ...this.userInfo }
      this.$refs.infoRef.resetFields()
    }
  },
  // 刷新直接获取数据
  watch: {
    userInfo (newValue, oldValue) {
      this.infoForm = newValue
    }
  },
  // mounted () {
  //   setTimeout(() => {
  //     this.infoForm = this.userInfo
  //   }, 1000)
  // },
  data () {
    return {
      // 表单信息对象
      infoForm: {},
      // 验证规则对象
      infoRuels: {
        nickname: [
          {
            required: true,
            message: '昵称不能为空',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^\S{1,10}$/,
            message: '昵称是1-10个非空字符',
            trigger: ['blur', 'change']
          }
        ],
        email: [
          {
            required: true,
            message: '邮箱不能为空',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z.]{2,6})$/,
            message: '邮箱格式不正确',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  }
}
</script>
